package cn.eastseven.demo.chat;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import org.springframework.stereotype.Component;

import cn.eastseven.demo.netty.common.Header;
import cn.eastseven.demo.netty.common.MessageType;
import cn.eastseven.demo.netty.common.NettyMessage;

@Component
@Sharable
public class HeartBeatRespHandler extends ChannelHandlerAdapter {

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		NettyMessage message = (NettyMessage) msg;
		if(message.getHeader() != null && message.getHeader().getType() == MessageType.HEARTBEAT_REQ) {
			NettyMessage heartBeat = buildHeartBeat();
			System.out.println("Receive client hb msg="+message+", Send hb response to client: "+heartBeat);
			ctx.writeAndFlush(heartBeat);
		} else {
			ctx.fireChannelRead(msg);
		}
	}
	
	private NettyMessage buildHeartBeat() {
		NettyMessage heartBeat = new NettyMessage();
		Header header = new Header();
		header.setType(MessageType.HEARTBEAT_RESP);
		heartBeat.setHeader(header);
		return heartBeat;
	}
}
